package cn.wolfcode.chatroom.core;

import cn.wolfcode.chatroom.core.domain.ChatroomMessage;
import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

abstract public class SessionContext {

    private static final AtomicInteger ONLINE_NUM = new AtomicInteger();
    private static final Map<String, WebSocketSession> SESSION_CONTEXT = new ConcurrentHashMap<>();

    public static void sendMsg(ChatroomMessage message) {
        try {
            // 当前消息是否为系统消息
            boolean user = message.getType() == ChatroomMessage.NORMAL;
            // 通知前端用户
            for (Map.Entry<String, WebSocketSession> entry : SESSION_CONTEXT.entrySet()) {
                // 获取用户名
                String username = entry.getKey();
                // 获取 session
                WebSocketSession session = entry.getValue();

                // 如果不是系统，且是当前用户，就直接跳过
                if (user && message.getSender().equals(username)) {
                    continue;
                }

                session.sendMessage(new TextMessage(JSON.toJSONString(message)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addSession(WebSocketSession session) {
        String username = getUsername(session);
        SESSION_CONTEXT.put(username, session);
        ONLINE_NUM.incrementAndGet();
    }

    public static void removeSession(WebSocketSession session) {
        String username = getUsername(session);
        SESSION_CONTEXT.remove(username);
        ONLINE_NUM.decrementAndGet();
    }

    public static String getUsername(WebSocketSession session) {
        return getParamValue("username", session);
    }

    public static String getParamValue(String name, WebSocketSession session) {
        String value = "";
        URI uri = session.getUri();
        if (uri != null) {
            String query = uri.getQuery();
            if (StringUtils.hasText(query)) {
                String[] params = query.split("&");
                for (String param : params) {
                    String[] paramArr = param.split("=");

                    if (name.equals(paramArr[0])) {
                        value = paramArr[1];
                        break;
                    }
                }
            }
        }
        return value;
    }

    public static int getOnlineNum() {
        return ONLINE_NUM.get();
    }
}
